package com.javaee.lpr.cotroller;

import com.javaee.lpr.entity.Notice;
import com.javaee.lpr.entity.User;
import com.javaee.lpr.service.IUserService;
import com.javaee.lpr.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController// Controller + ResponseBody
@RequestMapping("user")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @RequestMapping("reg")
    public JsonResult<Void> register(User user){
        userService.register(user);
        // 有异常就给BaseController
        return new JsonResult<>(OK);
    }

    @RequestMapping("log")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User user = userService.login(username, password);
        // 存储信息到全局session
        session.setAttribute("id", user.getId());
        session.setAttribute("username",user.getUsername());
        // 获取id 和 username
//        System.out.println(getIdFormSession(session));
//        System.out.println(getUsernameFormSession(session));
        return new JsonResult<User>(OK,user);
    }
    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session){
        Integer id = getIdFormSession(session);
        String username = getUsernameFormSession(session);
        userService.changePassword(id, username, oldPassword,newPassword);
        return new JsonResult<Void>(OK);
    }

    @RequestMapping("add_employee")
    public JsonResult<Void> addEmployee(User user){
        userService.addEmployee(user);
        // 有异常就给BaseController
        return new JsonResult<>(OK);
    }

    @RequestMapping("delete_employee")
    public JsonResult<Void> deleteEmployee(User user){
        userService.deleteEmployee(user);
        // 有异常就给BaseController
        return new JsonResult<>(OK);
    }

    @RequestMapping("add_notice")
    public JsonResult<Void> addNotice(Notice notice){
        userService.addNotice(notice);
        // 有异常就给BaseController
        return new JsonResult<>(OK);
    }
}
